package main

import (
	"bufio"
	"fmt"
	"github.com/sentiger/ftcp/Net"
	"io"
	"net"
	"strings"
	"time"
)

func main2() {
	str := "123456789123456789123456789"
	strRead := strings.NewReader(str)
	buf := bufio.NewReaderSize(strRead, 2)
	for {
		con := make([]byte, 3)
		n, err := buf.Read(con)
		if err != nil {
			break
		}
		fmt.Println(n, string(con[:n]))
	}
}

type Test struct {
	Index int
	Num   int
}

type student struct {
	Name string
	Age  int
}

func pase_student() {
	m := make(map[string]*student)
	stus := []student{
		{Name: "zhou", Age: 24},
		{Name: "li", Age: 23},
		{Name: "wang", Age: 22},
	}
	for _, stu := range stus {
		m[stu.Name] = &stu
	}

	for k, s := range m {
		fmt.Println(k, s)
	}

}

func main3() {
	pase_student()
}
func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8098")
	if err != nil {
		fmt.Println("client start err, exit!")
		return
	}
	for {
		//发封包message消息
		dp := Net.NewDataPack()
		msg, _ := dp.Pack(Net.NewMsgPackage(0, []byte("第二个")))
		_, err := conn.Write(msg)
		if err != nil {
			fmt.Println("write error err ", err)
			return
		}
		//先读出流中的head部分
		headData := make([]byte, dp.GetHeadLen())
		_, err = io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
		if err != nil {
			fmt.Println("read head error")
			break
		}
		//将headData字节流 拆包到msg中
		msgHead, err := dp.UnPack(headData)
		if err != nil {
			fmt.Println("server unpack err:", err)
			return
		}
		if msgHead.GetDataLen() > 0 {
			//msg 是有data数据的，需要再次读取data数据
			msg := msgHead.(*Net.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			//根据dataLen从io中读取字节流
			_, err := io.ReadFull(conn, msg.Data)
			if err != nil {
				fmt.Println("server unpack data err:", err)
				return
			}
			fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
		}
		time.Sleep(3 * time.Second)
	}
}
